<template>
  <el-dialog
    v-model="visible"
    width="800px"
    :before-close="handleClose"
    class="unified-dialog job-edit-dialog"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon header-icon-primary">
          <el-icon><Edit /></el-icon>
        </div>
        <div class="header-content">
          <h3>编辑作业</h3>
          <p>修改作业配置和参数设置</p>
        </div>
      </div>
    </template>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="left"
      class="job-edit-form"
    >
      <!-- 基础信息分组 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Document /></el-icon>
          <span>基础信息</span>
        </div>
        
        <el-form-item label="作业名称" prop="job_name" required>
          <el-input
            v-model="form.job_name"
            placeholder="请输入作业名称"
            clearable
            :disabled="true"
          />
          <span class="form-tip">作业名称不可修改</span>
        </el-form-item>
        
        <el-form-item label="作业描述" prop="job_description">
          <el-input
            v-model="form.job_description"
            type="textarea"
            :rows="2"
            placeholder="请输入作业描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="入口类" prop="entry_class" required>
          <el-input
            v-model="form.entry_class"
            placeholder="请输入主类全限定名，如：com.example.MainClass"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="程序参数" prop="program_args">
          <el-input
            v-model="form.program_args"
            type="textarea"
            :rows="3"
            placeholder="请输入程序启动参数，多个参数用空格分隔"
            maxlength="500"
            show-word-limit
          />
          <div class="param-templates">
            <el-button size="small" @click="applyTemplate('basic')">基础参数</el-button>
            <el-button size="small" @click="applyTemplate('test')">测试环境</el-button>
            <el-button size="small" @click="applyTemplate('dev')">开发环境</el-button>
            <el-button size="small" @click="applyTemplate('timestamp')">带时间戳</el-button>
            <el-button size="small" type="primary" @click="showTimestampPicker">
              <el-icon><Clock /></el-icon>
              生成时间戳
            </el-button>
          </div>
        </el-form-item>
      </div>
      
      <!-- 恢复设置分组 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Refresh /></el-icon>
          <span>恢复设置</span>
        </div>
        
        <el-form-item label="自动恢复" prop="auto_recovery">
          <div class="switch-container">
            <el-switch
              v-model="form.auto_recovery"
              :active-value="1"
              :inactive-value="0"
              size="large"
            />
            <div class="switch-description">
              <p class="description-title">启用自动恢复</p>
              <p class="description-text">作业异常停止时自动重启，提高作业稳定性</p>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="最大恢复次数" prop="max_recovery_attempts" required>
          <el-input-number
            v-model="form.max_recovery_attempts"
            :min="0"
            :max="100"
            controls-position="right"
            class="number-input"
          />
          <span class="form-tip">设置为0表示不限制恢复次数</span>
        </el-form-item>
        
        <el-form-item label="当前恢复次数" prop="recovery_attempts">
          <el-input-number
            v-model="form.recovery_attempts"
            :min="0"
            :max="100"
            controls-position="right"
            class="number-input"
            :disabled="true"
          />
          <span class="form-tip">系统自动维护，不可手动修改</span>
        </el-form-item>
      </div>
      
      <!-- 保存点设置分组 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Clock /></el-icon>
          <span>保存点设置</span>
        </div>
        
        <el-form-item label="保存点间隔" prop="savepoint_interval" required>
          <el-input-number
            v-model="form.savepoint_interval"
            :min="1"
            :max="168"
            controls-position="right"
            class="number-input"
          />
          <span class="form-tip">小时，建议设置为24小时</span>
        </el-form-item>
      </div>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 时间戳选择器弹窗 -->
  <el-dialog
    v-model="timestampPickerVisible"
    title="选择时间戳"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="timestamp-picker">
      <div class="timestamp-info-banner">
        <div class="info-icon">
          <el-icon><InfoFilled /></el-icon>
        </div>
        <div class="info-content">
          <h4 class="info-title">时间戳说明</h4>
          <p class="info-text">选择的时间将转换为毫秒时间戳并插入到参数中</p>
        </div>
      </div>
      
      <el-form label-width="100px">
        <el-form-item label="选择日期">
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
            :clearable="true"
            @change="handleDateChange"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          />
        </el-form-item>
        
        <el-form-item label="选择时间">
          <el-time-picker
            v-model="selectedTime"
            placeholder="选择时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :clearable="true"
            @change="handleTimeChange"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          />
        </el-form-item>
        
        <el-form-item label="时间戳预览">
          <el-input
            :value="timestampPreview"
            readonly
            placeholder="选择时间后显示时间戳"
          />
        </el-form-item>
        
        <el-form-item label="参数预览">
          <el-input
            :value="paramPreview"
            type="textarea"
            :rows="3"
            readonly
            placeholder="显示插入时间戳后的完整参数"
          />
        </el-form-item>
        
        <el-form-item label="快捷选择">
          <div class="quick-select-buttons">
            <el-button size="small" @click="setQuickTime('1h')" plain>1小时前</el-button>
            <el-button size="small" @click="setQuickTime('6h')" plain>6小时前</el-button>
            <el-button size="small" @click="setQuickTime('12h')" plain>12小时前</el-button>
            <el-button size="small" @click="setQuickTime('today')" plain>今天开始</el-button>
            <el-button size="small" @click="setQuickTime('yesterday')" plain>昨天开始</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="timestampPickerVisible = false">取消</el-button>
        <el-button type="primary" @click="insertTimestamp">
          插入时间戳
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useJobsStore } from '@/stores/jobs'
import { ElMessage } from 'element-plus'
import { Clock, InfoFilled } from '@element-plus/icons-vue'
import { componentLogger } from '@/utils/logger'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  job: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const jobsStore = useJobsStore()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref()
const loading = ref(false)

const form = ref({
  job_name: '',
  job_description: '',
  program_args: '',
  entry_class: '',
  auto_recovery: 1,
  max_recovery_attempts: 3,
  recovery_attempts: 0,
  savepoint_interval: 24
})

// 时间戳选择器相关状态
const timestampPickerVisible = ref(false)
const selectedDate = ref('')
const selectedTime = ref('')

// 日期快捷选择配置
const dateShortcuts = [
  {
    text: '今天',
    value: () => new Date()
  },
  {
    text: '明天',
    value: () => {
      const tomorrow = new Date()
      tomorrow.setDate(tomorrow.getDate() + 1)
      return tomorrow
    }
  },
  {
    text: '后天',
    value: () => {
      const dayAfterTomorrow = new Date()
      dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2)
      return dayAfterTomorrow
    }
  }
]

const rules = {
  job_name: [
    { required: true, message: '请输入作业名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  entry_class: [
    { required: true, message: '请输入入口类', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)*$/, 
      message: '请输入有效的Java类名，如：com.example.MainClass', 
      trigger: 'blur' 
    }
  ],
  job_description: [
    { max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }
  ],
  program_args: [
    { max: 500, message: '参数长度不能超过500个字符', trigger: 'blur' }
  ],
  max_recovery_attempts: [
    { required: true, message: '请输入最大恢复次数', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '恢复次数应在0-100之间', trigger: 'blur' }
  ],
  recovery_attempts: [
    { type: 'number', min: 0, max: 100, message: '恢复次数应在0-100之间', trigger: 'blur' }
  ],
  savepoint_interval: [
    { required: true, message: '请输入保存点间隔', trigger: 'blur' },
    { type: 'number', min: 1, max: 168, message: '保存点间隔应在1-168小时之间', trigger: 'blur' }
  ]
}

const handleClose = () => {
  visible.value = false
}

const initForm = () => {
  if (props.job) {
    form.value = {
      job_name: props.job.job_name || '',
      job_description: props.job.job_description || '',
      program_args: props.job.program_args || '',
      entry_class: props.job.entry_class || '',
      auto_recovery: props.job.auto_recovery || 0,
      max_recovery_attempts: props.job.max_recovery_attempts || 3,
      recovery_attempts: props.job.recovery_attempts || 0,
      savepoint_interval: props.job.savepoint_interval || 24
    }
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 使用统一的更新接口
    const updateData = {
      job_description: form.value.job_description,
      entry_class: form.value.entry_class,
      program_args: form.value.program_args,
      auto_recovery: form.value.auto_recovery,
      max_recovery_attempts: form.value.max_recovery_attempts,
      recovery_attempts: form.value.recovery_attempts,
      savepoint_interval: form.value.savepoint_interval,
      manual_stopped: 0  // 编辑时重置为0，表示用户主动配置，开启监控
    }
    
    const result = await jobsStore.updateJob(props.job.job_name, updateData)
    
    if (result.success) {
      ElMessage.success('作业更新成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    componentLogger.error('更新作业失败:', error)
    ElMessage.error('更新失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 监听对话框显示状态，初始化表单
watch(visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 监听job变化
watch(() => props.job, () => {
  if (visible.value) {
    initForm()
  }
}, { deep: true })

// 参数模板
const paramTemplates = {
  basic: '--parallelism 1 --env dev',
  test: '--parallelism 2 --env test',
  dev: '--parallelism 1 --env dev',
  timestamp: `--parallelism 1 --env test --timestamp ${Date.now()}`
}

const applyTemplate = (templateKey) => {
  const template = paramTemplates[templateKey]
  if (template) {
    form.value.program_args = template
    ElMessage.success(`已应用${templateKey}参数模板`)
  }
}

// 时间戳相关计算属性
const timestampPreview = computed(() => {
  if (!selectedDate.value || !selectedTime.value) return ''
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  return timestamp.toString()
})

const paramPreview = computed(() => {
  if (!selectedDate.value || !selectedTime.value) return ''
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  const timestampStr = `--timestamp ${timestamp}`
  
  const currentArgs = form.value.program_args.trim()
  if (!currentArgs) {
    return timestampStr
  }
  
  if (currentArgs.includes('--timestamp')) {
    return currentArgs.replace(/--timestamp\s+\d+/g, `--timestamp ${timestamp}`)
  } else {
    return currentArgs + ' ' + timestampStr
  }
})

// 显示时间戳选择器
const showTimestampPicker = () => {
  // 设置默认时间为当前时间
  const now = new Date()
  selectedDate.value = now.toISOString().slice(0, 10)
  selectedTime.value = now.toTimeString().slice(0, 8)
  timestampPickerVisible.value = true
}

// 处理日期变化
const handleDateChange = (value) => {
  componentLogger.info('日期选择器变化:', value)
  if (value) {
    componentLogger.info('选择的日期:', value)
  }
}

// 处理时间变化
const handleTimeChange = (value) => {
  componentLogger.info('时间选择器变化:', value)
  if (value) {
    componentLogger.info('选择的时间:', value)
  }
}

// 快捷时间选择
const setQuickTime = (type) => {
  const now = new Date()
  let targetTime
  
  switch (type) {
    case '1h':
      targetTime = new Date(now.getTime() - 1 * 60 * 60 * 1000)
      break
    case '6h':
      targetTime = new Date(now.getTime() - 6 * 60 * 60 * 1000)
      break
    case '12h':
      targetTime = new Date(now.getTime() - 12 * 60 * 60 * 1000)
      break
    case 'today':
      targetTime = new Date(now)
      targetTime.setHours(0, 0, 0, 0)
      break
    case 'yesterday':
      targetTime = new Date(now)
      targetTime.setDate(now.getDate() - 1)
      targetTime.setHours(0, 0, 0, 0)
      break
    default:
      targetTime = now
  }
  
  // 设置日期和时间
  selectedDate.value = targetTime.toISOString().split('T')[0]
  selectedTime.value = targetTime.toTimeString().split(' ')[0]
  
  const labels = {
    '1h': '1小时前',
    '6h': '6小时前',
    '12h': '12小时前',
    'today': '今天开始',
    'yesterday': '昨天开始'
  }
  ElMessage.success(`已设置为${labels[type] || '未知'}`)
}

// 插入时间戳
const insertTimestamp = () => {
  if (!selectedDate.value || !selectedTime.value) {
    ElMessage.warning('请先选择日期和时间')
    return
  }
  
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  const timestampStr = `--timestamp ${timestamp}`
  
  const currentArgs = form.value.program_args.trim()
  if (!currentArgs) {
    form.value.program_args = timestampStr
  } else {
    if (currentArgs.includes('--timestamp')) {
      form.value.program_args = currentArgs.replace(/--timestamp\s+\d+/g, `--timestamp ${timestamp}`)
    } else {
      form.value.program_args = currentArgs + ' ' + timestampStr
    }
  }
  
  timestampPickerVisible.value = false
  ElMessage.success(`已插入时间戳: ${timestamp}`)
}
</script>

<style scoped>
/* 对话框已使用统一样式系统 (dialog-system.css) */

.job-edit-form {
  max-height: 600px;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.form-section:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #409eff;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.section-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  padding: 8px;
  border-radius: 8px;
}

.form-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

.switch-container {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.switch-description {
  flex: 1;
}

.description-title {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.description-text {
  margin: 0;
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
}

.number-input {
  width: 120px;
}

/* 参数模板样式 */
.param-templates {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.param-templates .el-button {
  font-size: 12px;
  padding: 4px 8px;
  height: auto;
}

/* 时间戳选择器样式 */
.timestamp-picker {
  padding: 10px 0;
}

/* 时间戳说明横幅样式 */
.timestamp-info-banner {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px 20px;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #e0f2fe 0%, #dbeafe 100%);
  border-left: 4px solid #0284c7;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(2, 132, 199, 0.1);
  transition: all 0.3s ease;
}

.timestamp-info-banner:hover {
  box-shadow: 0 4px 16px rgba(2, 132, 199, 0.15);
  transform: translateY(-1px);
}

.info-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%);
  border-radius: 50%;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(2, 132, 199, 0.3);
}

.info-icon .el-icon {
  font-size: 24px;
  color: #ffffff;
}

.info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #0c4a6e;
  line-height: 1.4;
}

.info-text {
  margin: 0;
  font-size: 14px;
  color: #075985;
  line-height: 1.6;
}

.timestamp-picker .el-form-item {
  margin-bottom: 20px;
}

/* 优化只读输入框样式 - 更美观的展示效果 */
.timestamp-picker :deep(.el-input.is-disabled .el-input__wrapper),
.timestamp-picker :deep(.el-input[readonly] .el-input__wrapper),
.timestamp-picker :deep(.el-textarea.is-disabled .el-textarea__inner),
.timestamp-picker :deep(.el-textarea[readonly] .el-textarea__inner) {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 1px solid #bae6fd;
  color: #0369a1;
  font-weight: 500;
  cursor: default;
  box-shadow: 0 2px 8px rgba(3, 105, 161, 0.08);
}

.timestamp-picker :deep(.el-input[readonly] .el-input__inner) {
  color: #0369a1;
  font-weight: 500;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
}

.timestamp-picker :deep(.el-textarea[readonly] .el-textarea__inner) {
  color: #0369a1;
  font-weight: 500;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  line-height: 1.6;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

/* 表单项样式优化 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  color: #303133;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  resize: vertical;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner:hover) {
  border-color: #409eff;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
  border-radius: 8px;
}

:deep(.el-switch) {
  --el-switch-on-color: #409eff;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #66b3ff 0%, #409eff 100%);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

/* 滚动条样式 */
.job-edit-form::-webkit-scrollbar {
  width: 6px;
}

.job-edit-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.job-edit-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.job-edit-form::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .job-edit-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .switch-container {
    flex-direction: column;
    gap: 8px;
  }
  
  .number-input {
    width: 100%;
  }
}

/* 快捷选择按钮样式 */
.quick-select-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-select-buttons .el-button {
  border-radius: 16px;
  padding: 6px 16px;
  font-size: 13px;
  transition: all 0.3s ease;
  border: 1px solid #dcdfe6;
  background: #ffffff;
  color: #606266;
}

.quick-select-buttons .el-button:hover {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-color: #409eff;
  color: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.quick-select-buttons .el-button:active {
  transform: translateY(0);
}
</style>
